package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.Mediatype;
import com.qianniu.napi.admin.mapper.MconfigExtMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.AesUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.apache.commons.collections4.map.HashedMap;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 商家分店应用信息
 * </p>
 *
 * @author chenxuebin
 * @since 2018-08-22
 */
@Controller
public class MerchantAppController {

    private static final Logger logger = LoggerFactory.getLogger(MerchantAppController.class);

    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IMerchantAppService merchantappService;
    @Autowired
    private IMerchantConfigService merchantConfigService;
    @Autowired
    private IGoodsCategoryService goodsCategoryService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IFenxiaoService fenxiaoService;
    @Autowired
    private IFenxiaoFanService fenxiaoFanService;
    @Autowired
    private ICzfanService czfanService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private INavService navService;
    @Autowired
    private IMconfigExtService mconfigExtService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IChoujiangService choujiangService;
    @Autowired
    private IDisplayFenleiService displayFenleiService;
    @Autowired
    private ITemplatemsgService templatemsgService;
    @Autowired
    private INewsCategoryService newsCategoryService;
    @Autowired
    private ICoupontplExtService coupontplExtService;
    @Autowired
    private IMdpayService mdpayService;

    @Autowired
    private RedissonClient redis;

    @RequestMapping("admin/merchantapp/index")
    public String index(Model model) {
        User user = ObjectUtil.getSessionUser();
        logger.debug("======index user=", JSON.toJSONString(user));
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        if (ObjectUtil.getUserType() == 99) {
            List<MerchantApp> mapps = merchantappService.selectList(new EntityWrapper<MerchantApp>().setSqlSelect("id,name").eq("is_init", -1));
            model.addAttribute("mapps", mapps);
        }

        return "admin/merchantapp";
    }

    @RequestMapping("/admin/merchantapp/list")
    @ResponseBody
    public Page<MerchantApp> list(@RequestParam(value = "limit", required = false) int limit,
                                  @RequestParam(value = "offset", required = false) int offset) {
        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>();
        logger.debug(">>>>>>>>list  mid=" + ObjectUtil.getMid());
        logger.debug(">>>>>>>>list  mpid=" + ObjectUtil.getMpid());
        logger.debug(">>>>>>>>list  uid=" + ObjectUtil.getUid());
        logger.debug(">>>>>>>>list  getUserType=" + ObjectUtil.getUserType());
        if (ObjectUtil.getUserType() != 99) {
            wrapper.eq("mid", ObjectUtil.getMid());
        }
        wrapper.orderBy("id", true);
        Page<MerchantApp> page = merchantappService.selectPage(new Page<MerchantApp>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/merchantapp/add")
    public String add(MerchantApp bean, Model model) {
        logger.debug("========/admin/merchantapp/add start.......................");
        Merchant merchant = merchantService.selectById(ObjectUtil.getMid());

        bean.setCreatetime(new Date());
        bean.setMcode(merchant.getMcode());
        bean.setMid(ObjectUtil.getMid());
        bean.setUid(ObjectUtil.getUid());
        bean.setState(1);
        if (!Strings.isNullOrEmpty(bean.getMchid())) bean.setMchid(bean.getMchid().trim());
        if (!Strings.isNullOrEmpty(bean.getAppid())) bean.setAppid(bean.getAppid().trim());
        if (!Strings.isNullOrEmpty(bean.getPaykey())) bean.setPaykey(bean.getPaykey().trim());

        bean.setToken(StringUtil.getGUID());

        bean.insert();
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("MerchantApp@"+bean.getId()+"@insert", ActorRef.noSender());

        logger.debug("========MerchantApp insert OK");
        // 添加默认配置
        MerchantConfig mc = merchantConfigService.selectOne(new EntityWrapper<MerchantConfig>().eq("mid", bean.getMid())
                .eq("appid", bean.getAppid()));

        logger.debug("========MerchantApp = " + JSON.toJSONString(bean));
        logger.debug("========MerchantConfig insert start 111");
        try {
            if (mc == null) {
                mc = new MerchantConfig();
                mc.setMid(bean.getMid());
                mc.setMpid(bean.getId());
                mc.setAppid(bean.getAppid());
                mc.setUid(bean.getUid());

                mc.setIsHomeCategory(-1);
                mc.setIsShare(1);
                mc.setIsSearch(-1);
                mc.setIsNav(1);
                mc.setIsMember(-1);
                mc.setIsJifen(-1);

                mc.setIsCoupon(1);
                mc.setIsMiaotui(1);
                mc.setIsTmplmsg(1);
                mc.setIsMultishop(-1);
                mc.setIsEcashCard(-1);
                mc.setIsNotice(-1);
                mc.setIsBanner(1);

                mc.setIsHomeSearch(-1);
                mc.setBannerType(1);
                mc.setShowCategory(1);
                mc.setShowSalenum(-1);
                mc.setCategoryType(1);

                mc.setGoodsListType(1);
                mc.setListType(1);
                mc.setCategoryLevelType(1);
                mc.setSelltextType(1);

                mc.setJifenRate(1000);
                mc.setMaxJifen(1000000);
                mc.setMemberDiscountRate(new BigDecimal(1));
                mc.setMinTixian(new BigDecimal(10));
                mc.setTixianType(1);
                mc.setAboutType(0);
                mc.setVersion(1l);

                mc.setCreatetime(new Date());
                logger.debug("========MerchantConfig = " + JSON.toJSONString(mc));
                mc.insert();
                logger.debug("========MerchantConfig insert OK");
            }

            User muser = userService.selectOne(new EntityWrapper<User>().eq("mid", ObjectUtil.getMid()).eq("user_type", 31));
            if (muser != null) {
                muser.setMpid(bean.getId());
                //user_type 31:基础版
                //user_type 32:专业版
                //user_type 33:行业版
                //user_type 34:平台版
                //user_type 35:3DVR版
                //user_type 36:旗舰版
//                if(bean.getVersion()==1) muser.setUserType(31);
//                else if(bean.getVersion()==2&&muser.getUserType()<32)muser.setUserType(32);
//                else if(bean.getVersion()==3&&muser.getUserType()<33)muser.setUserType(33);
//                else if(bean.getVersion()==4&&muser.getUserType()<34)muser.setUserType(34);
//                else if(bean.getVersion()==5&&muser.getUserType()<35)muser.setUserType(35);
//                else if(bean.getVersion()==6&&muser.getUserType()<36)muser.setUserType(36);

                muser.updateById();
            }
            // 创建商家用户和密码
            muser = userService.selectOne(new EntityWrapper<User>().eq("username", bean.getMpcode()));

            muser = muser == null ? new User() : muser;

            muser.setUsername(bean.getMpcode());
            muser.setIsMch(1);
            muser.setIsPlatform(1);
            muser.setCreatetime(new Date());
            muser.setState(1);
            muser.setMpid(bean.getId());
            muser.setMid(bean.getMid());
//            muser.setUserType(31);// 默认商家专业版
            if (bean.getVersion() == 1) muser.setUserType(31);
            else if (bean.getVersion() == 2) muser.setUserType(32);
            else if (bean.getVersion() == 3) muser.setUserType(33);
            else if (bean.getVersion() == 4) muser.setUserType(34);
            else if (bean.getVersion() == 5) muser.setUserType(35);
            else if (bean.getVersion() == 6) muser.setUserType(36);
            muser.setApptype(bean.getAppType());
            muser.setPhoto(bean.getPic());
            muser.setGuid(StringUtil.getGUID());
            String pwd = bean.getMpcode() + "#" + ObjectUtil.randomStrings(6, 1).get(0);

            muser.setSalt(muser.getGuid().substring(0, 24));
            muser.setPassword(ObjectUtil.getPwd(pwd, muser.getSalt(), 3));

            muser.insertOrUpdate();

            // 创建用户角色

            UserRole userrole = userRoleService.selectOne(new EntityWrapper<UserRole>()
                    .eq("userid", muser.getId())
                    .eq("roleid", 1));

            userrole = userrole == null ? new UserRole() : userrole;
            userrole.setUserid(muser.getId());
            userrole.setRoleid(1l);// 默认1
            userrole.setState(1);// 默认1
            userrole.setMid(bean.getId());// 默认1
            userrole.setUid(muser.getId());// 默认1
            userrole.insertOrUpdate();

            // 新建默认分类
//            GoodsCategory cate = new GoodsCategory();
//            cate.setLevel(1);
//            cate.setName("全部商品");
//            cate.setKey("allgoods");
//            cate.setPaixu(1);
//            cate.setType("allgoods");
//
//            cate.setState(1);
//            cate.setUid(muser.getId());
//            cate.setMid(muser.getMid());
//            cate.setMpid(muser.getMpid());
//            cate.setCreatetime(new Date());
//            cate.insert();

            DisplayFenlei fenlei = new DisplayFenlei();

            fenlei.setName("全部商品");
            fenlei.setShowname("全部商品");
            fenlei.setType(0);// 全部商品
            fenlei.setSort(1);// 排序
            fenlei.setState(1);// 排序

//            fenlei.setCid(cate.getId());
            fenlei.setCid(0l);
//            fenlei.setMval(cate.getId().toString());
            fenlei.setMval("0");
            fenlei.setMkey("cid");
            fenlei.setMtype(1);// tab页类型
            fenlei.setMpath("/pages/category/category");// 默认分类页

            fenlei.setUid(muser.getId());
            fenlei.setMid(muser.getMid());
            fenlei.setMpid(muser.getMpid());
            fenlei.setCreatetime(new Date());
            fenlei.insert();
//            String[] displays = new String[]{"全部商品","店家推荐","拼团商品","砍价商品","限时购商品","爆款商品","抽奖商品","预约服务","实物商品"};
//            // 创建首页默认分类页
//            for(int i=0;i<=8;i++){
//                fenlei = new DisplayFenlei();
//
//                fenlei.setName(displays[i]);
//                fenlei.setShowname(displays[i]);
//                fenlei.setType(i);// 全部商品
//                fenlei.setSort(1);// 排序
//                fenlei.setListtype(2);// 排序
//
//                if(i==0)fenlei.setState(1);// 排序
//                else fenlei.setState(-1);// 排序
//
//                fenlei.setCid(bean.getId());
//                fenlei.setMval(bean.getId().toString());
//                fenlei.setMkey("cid");
//                fenlei.setMtype(1);// tab页类型
//                fenlei.setMpath("/pages/category/category");// 默认分类页
//
//                fenlei.setUid(muser.getId());
//                fenlei.setMid(muser.getMid());
//                fenlei.setMpid(muser.getMpid());
//                fenlei.setCreatetime(new Date());
//                fenlei.insert();
//            }

            model.addAttribute("pwd", pwd);
            model.addAttribute("idu", bean.getMpcode());
            model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());

        } catch (Exception e) {
            logger.error("========mc insert error", e);
        }
        return "admin/merchantapp";
    }

    @RequestMapping("/admin/merchantapp/initmkey")
    @ResponseBody
    public Jinfo initmkey(@RequestParam("mpid") String mpid) {

        Jinfo info = new Jinfo();
        MerchantApp ma = merchantappService.selectById(mpid);
        Long mid = ma.getMid();
//        生成规则 = mid+mpid+[uid]+random+appid+apptype
        // key = mid+"__"+mpid+"__uid__"+ ObjectUtil.randomStrings(8,1).get(0)+"__"+ma.getAppid()+"__"+ma.getAppType()[+"__"+sid+"__"+subsid][+"##"+main mpid];
        String mkey = mid + "__" + mpid + "____" + ObjectUtil.randomStrings(10, 1).get(0) + "__" + ma.getAppid() + "__" + ma.getAppType();
        if(ma.getAsmpid()!=null&&ma.getVersion()!=null&&ma.getVersion().intValue()==9)mkey+="##"+ma.getAsmpid();
        logger.debug(">>>>>>>>before encrypt mkey=", mkey);
        mkey = AesUtil.encrypt(mkey, Constants.ENCODE_KEY);
        logger.debug(">>>>>>>>after encrypt mkey=", mkey);
        info.setInfo(mkey);
        return info;
    }

    @RequestMapping("/admin/merchantapp/initmpwd")
    @ResponseBody
    public Jinfo initmpwd(long id, String pwd) {

        Jinfo jinfo = new Jinfo();
        MerchantApp mapp = merchantappService.selectById(id);
        if (mapp == null) {
            jinfo.setCode(4);
            jinfo.setMsg("参数有误");
            return jinfo;
        }
        String password = Strings.isNullOrEmpty(pwd) ? mapp.getMcode() + "#" + ObjectUtil.randomStrings(8, 1).get(0) : pwd;
        logger.debug("======new password=" + password);
        logger.debug("======new password=" + password);
        User muser = userService.selectOne(new EntityWrapper<User>().eq("username", mapp.getMpcode()).eq("mpid", id));
        if (muser == null) {
            muser = new User();

            muser.setUsername(mapp.getMpcode());
            muser.setIsMch(-1);
            muser.setIsPlatform(1);
            muser.setCreatetime(new Date());
            muser.setState(1);
            muser.setMid(mapp.getMid());
            muser.setMpid(id);
            muser.setUserType(31);// 默认商家专业版
            muser.setPhoto(mapp.getPic());
            muser.setGuid(StringUtil.getGUID());

            muser.setSalt(muser.getGuid().substring(0, 24));
            muser.setPassword(ObjectUtil.getPwd(password, muser.getSalt(), 3));

            muser.insert();

            UserRole userrole = new UserRole();
            userrole.setUserid(muser.getId());
            userrole.setRoleid(1l);// 默认1
            userrole.setState(1);// 默认1
            userrole.setMid(mapp.getMid());// 默认1
            userrole.setUid(muser.getId());// 默认1
            userrole.insert();

        } else {

            muser.setPassword(ObjectUtil.getPwd(password, muser.getSalt(), 3));
            muser.insertOrUpdate();
        }
        String msg = "请牢记账号密码：账号=" + mapp.getMpcode() + "，密码=" + password;
        jinfo.setInfo(msg);

        return jinfo;
    }

    @RequestMapping("/admin/merchantapp/setadmin")
    @ResponseBody
    public Jinfo setadmin(long id, String phone) {
        logger.debug("------------------------------------setadmin comming");
        Jinfo jinfo = new Jinfo();
        MerchantApp mapp = merchantappService.selectById(id);
        if (mapp == null || Strings.isNullOrEmpty(phone)) {
            jinfo.setCode(4);
            jinfo.setMsg("参数有误");
            return jinfo;
        }

        logger.debug("------------id=" + id);
        logger.debug("------------phone=" + phone);
        User muser = userService.selectOne(new EntityWrapper<User>()
                .eq("phone", phone).eq("mpid", id));
        if (muser == null) {
            jinfo.setCode(4);
            jinfo.setMsg("该手机号未登陆授权小程序或者未绑定小程序");
            return jinfo;
        } else {
            muser.setIsAdmin(1);
            muser.setIsPlatform(1);
            muser.setModifier(ObjectUtil.getUid());
            muser.setModifytime(new Date());

            String username = mapp.getMpcode() + phone.substring(7);
            String pwd = mapp.getMpcode() + phone.substring(3, 7);
            muser.setUsername(username);
            muser.setPassword(AesUtil.encrypt(pwd, Constants.ENCODE_PWD_KEY));

            muser.updateById();
            redisService.delUser(muser.getId());

            String msg = "请牢记账号密码：账号=" + username + "，密码=" + pwd;
            jinfo.setInfo(msg);
        }

        return jinfo;
    }

    @RequestMapping("/admin/merchantapp/getMerchantAppById")
    @ResponseBody
    public MerchantApp getMerchantAppById(long id) {
        MerchantApp merchantapp = merchantappService.selectById(id);

        return merchantapp;
    }

    @RequestMapping("/admin/merchantapp/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = merchantappService.deleteById(id);
        merchantConfigService.delete(new EntityWrapper<MerchantConfig>().eq("mpid", id));
        userService.delete(new EntityWrapper<User>().eq("mpid", id));
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/merchantapp/cloneapp")
    @ResponseBody
    public Jinfo cloneapp(long mpid, long targetmpid) {
        Jinfo jinfo = new Jinfo();
        logger.info("=============================================================mpid=" + mpid);
        logger.info("=============================================================targetmpid=" + targetmpid);
        MerchantApp source = merchantappService.selectById(mpid);
        if (source == null) {
            jinfo.setCode(4);
            return jinfo;
        }

        MerchantApp target = merchantappService.selectById(targetmpid);
        if (target == null) {
            jinfo.setCode(4);
            return jinfo;
        }

        logger.info("========================cloneapp source.getAsmpid()=" + source.getAsmpid());
        if (source.getAsmpid() != null) {
            target.setAsmpid(source.getAsmpid());
            String rkey = Constants.REDIS_MERCHANT_APP + targetmpid;
            redisService.del(rkey);
            redisService.set(rkey, target);
        }
        target.setIsInit(1);
        target.updateById();

//        else{
//            target.setAsmpid(mpid);
//        }

        // ================ define maps ===========
        Map<String, Long> categorymap = new HashedMap<String, Long>();
        Map<String, Long> goodsmap = new HashedMap<String, Long>();
        Map<String, Long> quanmap = new HashedMap<String, Long>();
        Map<String, Long> flmap = new HashMap<String, Long>();
        Map<String, String> configmap = new HashMap<String, String>();

        // clone config data
        List<Config> configs = configService.selectList(new EntityWrapper<Config>().eq("mpid", mpid));
        for (Config item : configs) {
            Long cid = item.getId();
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());

            item.insert();
            Long newcid = item.getId();
            configmap.put(cid.toString(), newcid.toString());
        }

        // clone goodscategory data + goods data + sku data
        List<GoodsCategory> cates = goodsCategoryService.selectList(new EntityWrapper<GoodsCategory>()
                .eq("mpid", mpid));
        List<GoodsCategory> catesgorys = goodsCategoryService.selectList(new EntityWrapper<GoodsCategory>()
                .eq("mpid", mpid));
        for (GoodsCategory item : cates) {
            Long cid = item.getId();

            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());
            item.insert();
            Long newcid = item.getId();

            categorymap.put(cid.toString(), newcid);
        }

        // clone youhuiquan data
        List<CouponTpl> quans = couponTplService.selectList(new EntityWrapper<CouponTpl>().eq("mpid", mpid));
        for (CouponTpl item : quans) {
            Long quanid = item.getId();
            item.setId(null);            //
            item.setMpid(targetmpid);    //
            item.setMid(target.getMid());//
            if (item.getCategories() != null) {
                String newcids = "";
                List<String> cids = Arrays.asList(item.getCategories().split(";"));
                for (String c : cids) {
                    newcids += c + ";";
                }
                item.setCategories(newcids);
            }
            if (item.getGids() != null) {
                String newcids = "";
                List<String> cids = Arrays.asList(item.getGids().split(";"));
                for (String c : cids) {
                    newcids += c + ";";
                }
                item.setGids(newcids);
            }
            item.setUse(0);
            item.setCreatetime(new Date());
            item.insert();
            quanmap.put(quanid.toString(), item.getId());
        }

        // clone shouye fenlei data
        List<DisplayFenlei> fenleis = displayFenleiService.selectList(new EntityWrapper<DisplayFenlei>()
                .eq("mpid", mpid));
        for (DisplayFenlei item : fenleis) {
            Long flid = item.getId();
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            logger.info("=========================================================item.getCid()=" + item.getCid());
            if (item.getCid() != null && categorymap.containsKey(item.getCid().toString()))
                item.setCid(categorymap.get(item.getCid().toString()));
            item.setCreatetime(new Date());

            item.insert();
            flmap.put(flid.toString(), item.getId());
        }

        for (GoodsCategory item : catesgorys) {
            Long cid = item.getId();
            logger.info("--------------------------------------------------------------------goods copy item.getId()=" + cid);
            List<Goods> glist = goodsService.selectList(new EntityWrapper<Goods>().eq("cid", cid));
            for (Goods gitem : glist) {
                Long gid = gitem.getId();
                Long newcid = categorymap.get(cid.toString());

                Long tplid = gitem.getTplid();
                Long newtplid = tplid != null && quanmap.containsKey(tplid.toString()) ? quanmap.get(tplid.toString()) : null;

                gitem.setId(null);
                gitem.setCid(newcid);
                gitem.setTplid(newtplid);

                if (gitem.getGdcid() != null) gitem.setGdcid(flmap.get(gitem.getGdcid().toString()));

                if (gitem.getGdcid() != null && flmap.containsKey(gitem.getGdcid().toString())) {

                    gitem.setGdcid(flmap.get(gitem.getGdcid().toString()));
                }
                gitem.setMpid(targetmpid);
                gitem.setMid(target.getMid());
                gitem.setCreatetime(new Date());
                gitem.insert();

                Long newgid = gitem.getId();
                goodsmap.put(gid.toString(), newgid);

                List<GoodsSku> skulist = goodsSkuService.selectList(new EntityWrapper<GoodsSku>().eq("gid", gid));
                for (GoodsSku skuitem : skulist) {
                    skuitem.setId(null);
                    skuitem.setCid(newcid);
                    skuitem.setGid(newgid);
                    skuitem.setMpid(targetmpid);
                    skuitem.setMid(target.getMid());
                    skuitem.setCreatetime(new Date());

                    skuitem.insert();
                }
            }
        }

        //默认添加预约服务+积分兑换类型
        //预约服务
        GoodsCategory yuyue = new GoodsCategory();
        yuyue.setName("预约服务");
        yuyue.setKey("01c161c6-a3bc-4a15-b189-e84edfd43172");
        yuyue.setLevel(1);
        yuyue.setPaixu(1);
        yuyue.setType("yuyue");

        yuyue.setState(1);
        yuyue.setIsNav(-1);
        yuyue.setIsdeleted(-1);
        yuyue.setMid(target.getMid());
        yuyue.setMpid(targetmpid);
        yuyue.setCreatetime(new Date());
        yuyue.insert();

        //积分兑换
        GoodsCategory goodsCategory = new GoodsCategory();
        goodsCategory.setName("积分兑换");
        goodsCategory.setKey("612f71a1-a1e9-4a04-917b-566fa1ae7889");
        goodsCategory.setLevel(1);
        goodsCategory.setPaixu(1);
        goodsCategory.setType("jifen");

        goodsCategory.setState(1);
        goodsCategory.setIsNav(-1);
        goodsCategory.setIsdeleted(-1);
        goodsCategory.setMid(target.getMid());
        goodsCategory.setMpid(targetmpid);
        goodsCategory.setCreatetime(new Date());
        goodsCategory.insert();

        // clone mappconfig data
        MerchantConfig smconfig = merchantConfigService.selectOne(new EntityWrapper<MerchantConfig>().eq("mpid", mpid));
        MerchantConfig tmconfig = merchantConfigService.selectOne(new EntityWrapper<MerchantConfig>().eq("mpid", targetmpid));

        smconfig.setId(null);
        smconfig.setAppid(target.getAppid());
        smconfig.setMid(target.getMid());
        smconfig.setMpid(targetmpid);
        smconfig.setCreatetime(new Date());

        smconfig.insert();
        if (tmconfig != null) tmconfig.deleteById();

        redisService.del(Constants.REDIS_MERCHANT_CONFIG + mpid);
        redisService.del(Constants.REDIS_MERCHANT_CONFIG + targetmpid);

        // =================== fenxiao + fenxiaofan + chongzhifan ===================
        // clone fenxiao data
        List<Fenxiao> fxiaos = fenxiaoService.selectList(new EntityWrapper<Fenxiao>().eq("mpid", mpid));
        for (Fenxiao item : fxiaos) {
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());

            item.insert();
        }
        // ===================fenxiao end ===================

        // clone fenxiaofan data
        List<FenxiaoFan> fxfans = fenxiaoFanService.selectList(new EntityWrapper<FenxiaoFan>().eq("mpid", mpid));
        for (FenxiaoFan item : fxfans) {
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());

            item.insert();
        }
        // ===================fenxiaofan end ===================

        // clone chongzhifan data
        List<Czfan> czfans = czfanService.selectList(new EntityWrapper<Czfan>().eq("mpid", mpid));
        for (Czfan item : czfans) {
            item.setId(null);
            if (item.getFangoods() != null) item.setFangoods(goodsmap.get(item.getFangoods().toString()));
            if (item.getFanquan() != null) item.setFanquan(quanmap.get(item.getFanquan().toString()));
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());

            item.insert();
        }
        // ===================chongzhifan end ===================

        // clone templatemsg data
        List<Templatemsg> templatemsgs = templatemsgService.selectList(new EntityWrapper<Templatemsg>().eq("mpid", mpid));
        for (Templatemsg item : templatemsgs) {
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setTplid("");
            item.setCreatetime(new Date());

            item.insert();
        }
        // ===================templatemsg end ===================

        // =================== Choujiang + banner + nav ===================
        // clone Choujiang data
        List<Choujiang> choujiangs = choujiangService.selectList(new EntityWrapper<Choujiang>().eq("mpid", mpid));
        for (Choujiang item : choujiangs) {
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());

            if (item.getGid() != null) item.setGid(goodsmap.get(item.getGid().toString()));
            if (item.getJtype() == 2 && item.getJid() != null) {//优惠券
                item.setJid(quanmap.get(item.getJid().toString()));
            }
            if (item.getJtype() == 3 && item.getJid() != null) {//商品
                item.setJid(goodsmap.get(item.getJid().toString()));
            }
            item.insert();
        }

        // clone banner data
        List<Banner> banners = bannerService.selectList(new EntityWrapper<Banner>().eq("mpid", mpid));
        for (Banner item : banners) {
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());

            item.insert();
        }

        // clone nav data
        List<Nav> navs = navService.selectList(new EntityWrapper<Nav>().eq("mpid", mpid));
        for (Nav item : navs) {
            item.setId(null);
            item.setMpid(targetmpid);
            item.setMid(target.getMid());
            item.setCreatetime(new Date());
            if (!Strings.isNullOrEmpty(item.getNvalue()) && configmap.containsKey(item.getNvalue())) {
                item.setNvalue(configmap.get(item.getNvalue()));
            }

            item.insert();
        }

        // clone t_mconfig_ext data
        MconfigExt mconfigExt = mconfigExtService.selectOne(new EntityWrapper<MconfigExt>().eq("mpid", mpid));
        if (mconfigExt != null) {
            mconfigExt.setMpid(targetmpid);
            mconfigExt.insert();
        }

        // clone t_mconfig_ext data
        CoupontplExt coupontplExt = coupontplExtService.selectOne(new EntityWrapper<CoupontplExt>().eq("mpid", mpid));
        if (coupontplExt != null) {
            coupontplExt.setMpid(targetmpid);
            coupontplExt.setMid(target.getMid());
            mconfigExt.insert();
        }

        // clone t_mdpay data
        Mdpay mdpay = mdpayService.selectById(-mpid);
        if (mdpay != null) {
            mdpay.setMpid(targetmpid);
            mdpay.setSid(-targetmpid);
            mdpay.insert();
        }
        // =================== end ===================

        return jinfo;
    }

    @RequestMapping("/admin/merchantapp/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        MerchantApp bean = new MerchantApp();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        merchantappService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/merchantapp/modify")
    public String update(MerchantApp bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        if (!Strings.isNullOrEmpty(bean.getMchid())) bean.setMchid(bean.getMchid().trim());
        if (!Strings.isNullOrEmpty(bean.getAppid())) bean.setAppid(bean.getAppid().trim());
        if (!Strings.isNullOrEmpty(bean.getPaykey())) bean.setPaykey(bean.getPaykey().trim());

        String rkey = Constants.REDIS_MERCHANT_APP + bean.getId();
        redisService.del(rkey);
        boolean isSuccc = merchantappService.updateById(bean);
        if (isSuccc) {
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("MerchantApp@"+bean.getId()+"@update", ActorRef.noSender());
            return "redirect:index";
        }

        return "error";
    }

    @RequestMapping("/admin/merchantapp/delappdata")
    @ResponseBody
    public Jinfo delappdata(Long mpid, String token) {
        Jinfo info = new Jinfo();
        String tk = "215b21c5c0c6c4e6a96d0a442cf7695e";
        if (Strings.isNullOrEmpty(token) || !token.equals(tk)) {
            info.setCode(4);
            return info;
        }
        // delete from t_goods_category where mpid=mpid
        goodsCategoryService.delete(new EntityWrapper<GoodsCategory>().eq("mpid", mpid));
        // delete from t_config where mpid=mpid
        configService.delete(new EntityWrapper<Config>().eq("mpid", mpid));
        // delete from t_coupon_tpl where mpid=mpid
        couponTplService.selectOne(new EntityWrapper<CouponTpl>().eq("mpid", mpid));
        // delete from t_coupontpl_ext where mpid=mpid
        coupontplExtService.delete(new EntityWrapper<CoupontplExt>().eq("mpid", mpid));

        // delete from t_mconfig_ext where mpid=mpid
        mconfigExtService.delete(new EntityWrapper<MconfigExt>().eq("mpid", mpid));
        // delete from t_nav where mpid=mpid
        navService.delete(new EntityWrapper<Nav>().eq("mpid", mpid));
        // delete from t_banner where mpid=mpid
        bannerService.delete(new EntityWrapper<Banner>().eq("mpid", mpid));
        // delete from t_choujiang where mpid=mpid
        choujiangService.delete(new EntityWrapper<Choujiang>().eq("mpid", mpid));

        // delete from t_templatemsg where mpid=mpid
        templatemsgService.delete(new EntityWrapper<Templatemsg>().eq("mpid", mpid));
        // delete from t_czfan where mpid=mpid
        czfanService.delete(new EntityWrapper<Czfan>().eq("mpid", mpid));
        // delete from t_fenxiao where mpid=mpid
        fenxiaoService.delete(new EntityWrapper<Fenxiao>().eq("mpid", mpid));
        // delete from t_fenxiao_fan where mpid=mpid
        fenxiaoFanService.delete(new EntityWrapper<FenxiaoFan>().eq("mpid", mpid));

        // delete from t_goods where mpid=mpid
        goodsService.selectOne(new EntityWrapper<Goods>().eq("mpid", mpid));
        // delete from t_goods_sku where mpid=mpid
        goodsSkuService.selectOne(new EntityWrapper<GoodsSku>().eq("mpid", mpid));
        // delete from t_display_fenlei where mpid=mpid
        displayFenleiService.selectOne(new EntityWrapper<DisplayFenlei>().eq("mpid", mpid));

        MerchantApp merchantApp = merchantappService.selectById(mpid);
        merchantApp.setIsInit(-1);
        merchantApp.updateById();

        return info;
    }

    @RequestMapping("/api/merchantapp/clearredis")
    @ResponseBody
    public Jinfo list(long id) {
        Jinfo info = new Jinfo();
        Long mid = ObjectUtil.getMid();
        MerchantApp mapp = merchantappService.selectById(id);
        String grkey = "";

        String rkey = Constants.REDIS_MERCHANT_APP + mapp.getId();
        RBucket<MerchantApp> bucket = redis.getBucket(rkey);
        if (bucket.isExists()) redisService.del(rkey);

        rkey = Constants.REDIS_APP_INIT + ObjectUtil.getMpid();
        RBucket<IndexInfo> IndexInfo = redis.getBucket(rkey);
        if (IndexInfo.isExists()) redisService.del(rkey);

        List<GoodsCategory> gsc = goodsCategoryService.selectList(new EntityWrapper<GoodsCategory>().eq("mid", mid).eq("level", 1));
        for (GoodsCategory item : gsc) {

            rkey = Constants.REDIS_CATEGORY_LIST + mid + "_" + ObjectUtil.getAppid() + "_" + item.getId();
            RBucket<List<GoodsCategory>> gcbucket = redis.getBucket(rkey);
            if (gcbucket.isExists()) gcbucket.delete();

            grkey = Constants.REDIS_GOODS_LIST + mid + "_" + ObjectUtil.getMpid() + "_" + item.getId() + "_";
            for (int i = 1; i <= 10; i++) {
                redisService.del(grkey + i);
            }
            RBucket<List<Goods>> goodsbucket = redis.getBucket(grkey);
            if (goodsbucket.isExists()) goodsbucket.delete();
        }

        return info;
    }


    @RequestMapping(value = "/admin/merchantapp/uploadPayfile", method = RequestMethod.POST)
//    @ResponseBody
    public String uploadPayfile(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                                @RequestParam(value = "tid", required = true) Long id) {
        Jinfo info = new Jinfo();

        if (mfile != null) {
            MerchantApp mapp = merchantappService.selectById(id);
            if (mapp == null) {
                info.setCode(4);
                info.setMsg("商家应用配置未找到");
//                return info;
                return "redirect:index";
            }

            String dirpath = Constants.PAYKEY_UPLOAD_PATH + mapp.getMcode() + "/" + mapp.getMpcode() + "/";

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String filepath = dirpath + "apiclient_cert.p12";

            File file = new File(filepath);// 保持原有文件格式
            if (file.exists()) {
                file.delete();
            }

            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            //保存
            try {
                file.createNewFile();
                logger.debug(">>>start to FileOutputStream");

                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                }
                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }

            try {
                Runtime.getRuntime().exec("chmod 644 " + filepath);
            } catch (Exception e) {
                logger.warn("Runtime.getRuntime error", e);
            }

        }
        return "redirect:index";
    }


}
